package club.itstudio.itouc.service.schedule

import club.itstudio.itouc.config.AdminConfig
import club.itstudio.itouc.config.ElectiveCoursecConfig
import club.itstudio.itouc.config.LessonConfig
import club.itstudio.itouc.core.util.logger
import club.itstudio.itouc.core.util.mapper
import club.itstudio.itouc.util.Redis
import com.fasterxml.jackson.module.kotlin.readValue
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service

@Service
class UpdateConfig(val ecConfig: ElectiveCoursecConfig,
                   val redis: Redis,
                   val lessonConfig: LessonConfig,
                   val adminConfig: AdminConfig)  {

    val logger = logger()

    @Scheduled(cron = "0 0/10 * * * ? ")
    fun updateEcConfig() {
        // 更新选课配置信息
        val ecConfigStr = redis.getEcConfigStr()
        if (ecConfigStr.isNotEmpty()) {
            val newEcConfig: ElectiveCoursecConfig =  mapper.readValue(ecConfigStr)
            if (newEcConfig.timestamp > ecConfig.timestamp) {
                ecConfig.year = newEcConfig.year
                ecConfig.semester = newEcConfig.semester
                ecConfig.open = newEcConfig.open
                ecConfig.refresh = newEcConfig.refresh
                ecConfig.timestamp = newEcConfig.timestamp
                logger.info("更新选课配置信息 $newEcConfig")
            }
        }

        // 更新课程配置信息
        val lessonConfigStr = redis.getLessonConfigStr()
        if (lessonConfigStr.isNotEmpty()) {
            val newLessonConfig: LessonConfig = mapper.readValue(lessonConfigStr)
            if (newLessonConfig.timestamp > lessonConfig.timestamp) {
                for(i in newLessonConfig.startDate.indices)
                    lessonConfig.startDate[i] = newLessonConfig.startDate[i]
                lessonConfig.year = newLessonConfig.year
                lessonConfig.semester = newLessonConfig.semester
                lessonConfig.dateReplaceMap.clear()
                lessonConfig.dateReplaceMap.putAll(newLessonConfig.dateReplaceMap)
                lessonConfig.dateHolidaySet.clear()
                lessonConfig.dateHolidaySet.addAll(newLessonConfig.dateHolidaySet)
                lessonConfig.timestamp = newLessonConfig.timestamp
                logger.info("更新课程信息配置 $newLessonConfig")
            }
        }

        // 更新管理员配置
        val adminConfigStr = redis.getAdminConfigStr()
        if (adminConfigStr.isNotEmpty()) {
            val newAdminConfig: AdminConfig = mapper.readValue(adminConfigStr)
            if (newAdminConfig.timeStamp > adminConfig.timeStamp) {
                adminConfig.adminSet.clear()
                adminConfig.adminSet.addAll(newAdminConfig.adminSet)
                adminConfig.timeStamp = newAdminConfig.timeStamp
                logger.info("更新管理员信息 $newAdminConfig")
            }
        }


    }
}